package com.example.developerlab;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.text.TextUtils;
import android.widget.Button;

import java.util.TimeZone;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class CalendarActivity extends Activity {
	private static String CALENDAR_URL = "content://com.android.calendar/calendars";
	private static String CALENDAR_EVENT_URL = "content://com.android.calendar/events";
	private static String CALENDAR_REMINDER_URL = "content://com.android.calendar/reminders";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendar);

		// 增加日历提醒
		Button button = findViewById(R.id.btn_add_remind);
		button.setOnClickListener(v -> {
			CalendarActivityPermissionsDispatcher.writeCalendarWithPermissionCheck(CalendarActivity.this);
		});

		// 打开系统日历
		Button btnOpenCalendarApp = findViewById(R.id.btn_open_calendar_app);
		btnOpenCalendarApp.setOnClickListener(v -> {
			gotoCalendar();
		});
	}

	private void gotoCalendar() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_APP_CALENDAR);
		startActivity(intent);
	}

	@NeedsPermission({Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR})
	public void writeCalendar() {
		insertCalendarEvent(this, "test-title", "test-des", System.currentTimeMillis(),
				System.currentTimeMillis() + 60 * 60 * 1000);
	}

	public static boolean insertCalendarEvent(Context context, String title, String description,
											  long beginTimeMillis, long endTimeMillis) {
		if (context == null || TextUtils.isEmpty(title) || TextUtils.isEmpty(description)) {
			return false;
		}

		int calId = checkCalendarAccount(context); // 获取日历账户的id
		if (calId < 0) { // 获取账户id失败直接返回，添加日历事件失败
			return false;
		}

		try {
			/** 插入日程 */
			ContentValues eventValues = new ContentValues();
			eventValues.put(CalendarContract.Events.DTSTART, beginTimeMillis); // 事件起始时间
			eventValues.put(CalendarContract.Events.DTEND, endTimeMillis); // 事件结束时间
			eventValues.put(CalendarContract.Events.TITLE, title); // 事件标题
			eventValues.put(CalendarContract.Events.DESCRIPTION, description); // 事件描述
			eventValues.put(CalendarContract.Events.CALENDAR_ID, 1); // 使用默认日历目录
			eventValues.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID()); // 获取默认时区
			Uri eUri = context.getContentResolver().insert(Uri.parse(CALENDAR_EVENT_URL), eventValues);
			long eventId = ContentUris.parseId(eUri);
			if (eventId == 0) { // 插入失败
				return false;
			}

			/** 插入提醒 - 依赖插入日程成功 */
			ContentValues reminderValues = new ContentValues();
			reminderValues.put(CalendarContract.Reminders.EVENT_ID, eventId);
			reminderValues.put(CalendarContract.Reminders.MINUTES, 10); // 提前10分钟提醒
			reminderValues.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); // 提示方式提醒
			Uri rUri = context.getContentResolver().insert(Uri.parse(CALENDAR_REMINDER_URL),
					reminderValues);
			if (rUri == null || ContentUris.parseId(rUri) == 0) {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	private static int checkCalendarAccount(Context context) {
		Cursor userCursor = context.getContentResolver().query(Uri.parse(CALENDAR_URL),
				null, null, null, null);
		try {
			if (userCursor == null) { // 查询返回空值
				return -1;
			}
			int count = userCursor.getCount();
			if (count > 0) { // 存在现有账户，取第一个账户的id返回
				userCursor.moveToFirst();
				return userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID));
			} else {
				return -1;
			}
		} finally {
			if (userCursor != null) {
				userCursor.close();
			}
		}
	}
}
